from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager, BaseUserManager, AbstractBaseUser
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import PermissionManager
from django.contrib.auth import authenticate

#
# class Person(User):
#     class Meta:
#         # 代理模型，操作Person，实际上就是操作User，不能在代理模型添加新的field
#         # 为了增加更多操作
#         proxy = True
#
#     @classmethod
#     def get_back(cls):
#         return cls.objects.first(is_active=False)
#     # 在其他文件中可以直接利用Person.get_back调用，因为原来的User不能直接获取黑名单
#




# class UserExtension(models.Model):
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     school = models.CharField(max_length=100)
#     phone = models.CharField(max_length=11)
#
#
# @receiver(post_save, sender=User)
# def handle_user_extension(sender, instance, created, **kwargs):
#     if created:
#         UserExtension.objects.create(user=instance)
#     else:
#         instance.extension.save()


# class UserManager(BaseUserManager):
#     """
#     实现User的 object功能
#     """
#     def _create_user(self, telephone, username, password, **kwargs):
#         user = self.model(telephone=telephone, username=username, **kwargs)
#         user.set_password(password)
#         user.save()
#         return user
#
#     def create_user(self, telephone, username, password, **kwargs):
#         kwargs['is_superuser'] = False
#         return self._create_user(telephone, username, password, **kwargs)
#
#     def create_superuser(self, telephone, username, password, **kwargs):
#         kwargs['is_superuser'] = True
#         return self._create_user(telephone, username, password, **kwargs)
#
#
# # 继承在做数据库迁移时，必须是第一次映射
# class User(AbstractUser):
#     phone = models.CharField(max_length=11, unique=True)
#     school = models.CharField(max_length=100)
#
#     # 这个from django.contrib.auth import authenticate函数验证的不再是username,但还是叫username，只是带表的是phone
#     USERNAME_FIELD = 'phone'


class User(AbstractBaseUser, PermissionManager):
    email = models.CharField(max_length=110, unique=True)
    phone = models.CharField(max_length=11, unique=True)
    school = models.CharField(max_length=100)
    username = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = []

    objects = UserManager()

    class Meta:
        permissions = [('view_user', '看')]
